<template>
  <div class="min-h-screen bg-white font-sans">
    <div class="flex min-h-[calc(100vh-4rem)] max-w-7xl mx-auto relative">
      <!-- 左侧边栏 -->
      <aside 
        class="w-70 bg-slate-50 border-r border-slate-200 overflow-y-auto absolute left-0 top-0 bottom-0 z-10 transition-transform duration-300 ease-in-out"
        :class="{ 'transform -translate-x-full': !sidebarOpen, 'transform translate-x-0': sidebarOpen, 'lg:translate-x-0': true }"
        style="height: calc(100vh - 4rem);"
      >
        <div class="py-6">
          <nav>
            <div class="mb-2" v-for="chapter in chapters" :key="chapter.id">
              <div 
                class="flex items-center px-6 py-2 font-semibold text-gray-700 cursor-pointer transition-all duration-200 ease-in-out select-none hover:bg-slate-200 hover:text-blue-600"
                @click="toggleChapter(chapter.id)"
                :class="{ 'text-blue-600': expandedChapters.includes(chapter.id) }"
              >
                <span class="mr-2 transition-transform duration-200 ease-in-out" :class="{ 'rotate-90': expandedChapters.includes(chapter.id) }">
                  <svg width="12" height="12" viewBox="0 0 24 24">
                    <path 
                      fill="currentColor" 
                      d="M8.59 16.58L13.17 12 8.59 7.41 10 6l6 6-6 6-1.41-1.42z"
                    />
                  </svg>
                </span>
                {{ chapter.title }}
              </div>
              <div 
                class="pl-4"
                v-show="expandedChapters.includes(chapter.id)"
              >
                <a 
                  v-for="lecture in chapter.lectures"
                  :key="lecture.id"
                  class="flex items-center px-6 py-1.5 text-gray-500 cursor-pointer transition-all duration-200 ease-in-out rounded mx-2 my-0.5 hover:bg-slate-200 hover:text-gray-700"
                  :class="{ 'bg-blue-50 text-blue-600 font-medium': selectedLecture?.id === lecture.id }"
                  @click="selectLecture(lecture)"
                >
                  <span class="mr-2 opacity-70">
                    <svg width="14" height="14" viewBox="0 0 24 24">
                      <path 
                        fill="currentColor" 
                        d="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20Z"
                      />
                    </svg>
                  </span>
                  {{ lecture.title }}
                </a>
              </div>
            </div>
          </nav>
        </div>
      </aside>

      <!-- 主内容区域 -->
      <main class="flex-1 lg:ml-70 min-h-[calc(100vh-4rem)] relative">
        <!-- 移动端菜单切换按钮 -->
        <button 
          class="lg:hidden fixed top-[4.5rem] left-4 z-20 flex flex-col justify-around w-6 h-6 bg-white border border-slate-200 rounded cursor-pointer p-1 shadow-lg"
          @click="toggleSidebar"
        >
          <span class="w-full h-0.5 bg-slate-700 transition-all duration-300 ease-in-out" :class="{ 'transform rotate-45 translate-x-1 translate-y-1': sidebarOpen }"></span>
          <span class="w-full h-0.5 bg-slate-700 transition-all duration-300 ease-in-out" :class="{ 'opacity-0': sidebarOpen }"></span>
          <span class="w-full h-0.5 bg-slate-700 transition-all duration-300 ease-in-out" :class="{ 'transform -rotate-45 translate-x-1.5 -translate-y-1.5': sidebarOpen }"></span>
        </button>
        
        <div class="max-w-6xl mx-auto p-8 lg:pt-8 pt-16">
          <!-- 加载状态 -->
          <div v-if="loading" class="flex flex-col items-center justify-center py-16 text-gray-500">
            <div class="w-8 h-8 border-3 border-slate-200 border-t-blue-600 rounded-full animate-spin mb-4"></div>
            <p>加载章节数据中...</p>
          </div>
          
          <!-- 错误状态 -->
          <div v-else-if="error" class="text-center py-16 px-8">
            <div class="text-red-500 mb-4">
              <svg class="w-16 h-16 mx-auto mb-4" fill="currentColor" viewBox="0 0 20 20">
                <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clip-rule="evenodd" />
              </svg>
            </div>
            <h2 class="text-2xl font-bold text-gray-900 mb-2">加载失败</h2>
            <p class="text-gray-600 mb-4">{{ error }}</p>
            <button 
              @click="fetchChapters" 
              class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
            >
              重试
            </button>
          </div>
          
          <!-- 欢迎页面 -->
          <div v-else-if="!selectedLecture" class="text-center py-16 px-8">
            <div>
              <h1 class="text-5xl font-bold text-gray-900 mb-4">欢迎来到课程讲义系统</h1>
              <p class="text-lg text-gray-500 mb-12 max-w-2xl mx-auto">
                请从左侧菜单选择要查看的课程章节和具体讲义内容。
              </p>
              <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-auto-fit gap-6 max-w-4xl mx-auto">
                <div class="bg-slate-50 border border-slate-200 rounded-xl p-6 text-center transition-all duration-200 ease-in-out hover:-translate-y-0.5 hover:shadow-xl" v-for="chapter in chapters" :key="chapter.id">
                  <div class="text-3xl font-bold text-blue-600 mb-2">{{ chapter.lectures.length }}</div>
                  <div class="text-sm text-gray-500 font-medium">{{ chapter.title }}</div>
                </div>
              </div>
            </div>
          </div>

          <!-- 讲义内容 -->
          <div v-if="selectedLecture" class="max-w-none">
            <!-- 内容头部 -->
            <div class="mb-2 pb-4 border-b border-slate-200">
              <div class="flex items-center mb-4 text-sm text-gray-500">
                <span class="text-gray-500">课程讲义</span>
                <span class="mx-2 text-gray-300">/</span>
                <span class="text-gray-500">{{ getCurrentChapter()?.title }}</span>
                <span class="mx-2 text-gray-300">/</span>
                <span class="text-gray-700 font-medium">{{ selectedLecture.title }}</span>
              </div>
              <h1 class="text-3xl font-bold text-gray-900 m-0">{{ selectedLecture.title }}</h1>
            </div>

            <!-- PDF 内容 -->
            <div v-if="isPdfFile(selectedLecture.file_type)" class="bg-white border border-slate-200 rounded-lg overflow-hidden">
              <VuePdfEmbed
                :source="selectedLecture.file_path"
                class="w-full min-h-[600px]"
              />
            </div>

            <!-- Markdown 内容 -->
            <div v-else class="bg-white flex">
              <!-- 主要内容区域 -->
              <div class="flex-1 min-w-0 overflow-y-auto" style="height: calc(100vh - 4rem);">
                <div class="p-2 max-w-4xl mx-auto">
                  <div ref="contentContainer" class="flex-1 min-w-0">
                    <div 
                      v-if="lectureContent" 
                      class="prose max-w-none text-gray-700 leading-relaxed" 
                      v-html="lectureContent"
                    ></div>
                    <div v-else class="flex flex-col items-center justify-center py-16 text-gray-500">
                      <div class="w-8 h-8 border-3 border-slate-200 border-t-blue-600 rounded-full animate-spin mb-4"></div>
                      <p>加载中...</p>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 右侧目录 -->
              <div v-if="tableOfContents.length > 0" class="w-64 flex-shrink-0 border-l border-slate-200">
                <div class="absolute top-0 right-0 w-64 h-[calc(100vh-4rem)] overflow-y-auto bg-white">
                  <div class="p-4">
                    <details class="bg-slate-50 border border-slate-200 rounded-lg p-4 w-full" open>
                      <summary class="font-semibold text-gray-700 mb-3 cursor-pointer list-none">
                        目录
                      </summary>
                      <nav class="flex flex-col gap-1">
                        <a
                          v-for="item in tableOfContents"
                          :key="item.id"
                          class="block py-1 px-2 text-gray-500 no-underline rounded text-xs cursor-pointer transition-all duration-200 ease-in-out hover:bg-slate-200 hover:text-gray-700"
                          :class="{
                            'font-semibold': item.level === 1,
                            'pl-4': item.level === 2,
                            'pl-6': item.level === 3,
                            'pl-8': item.level === 4
                          }"
                          @click="scrollToHeading(item.id)"
                        >
                          {{ item.text }}
                        </a>
                      </nav>
                    </details>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </main>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import VuePdfEmbed from 'vue-pdf-embed'
import { marked } from 'marked'

// 配置marked渲染器
let markdownRenderer: any = null

interface Lecture {
  id: number
  title: string
  content?: string
  file_path?: string
  file_type: string
  order_index: number
  chapter_id: number
  created_at?: string
  updated_at?: string
}

interface Chapter {
  id: number
  title: string
  description?: string
  order_index: number
  created_at?: string
  updated_at?: string
  lectures: Lecture[]
}

// API配置
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || '/api'
const STATIC_BASE_URL = import.meta.env.VITE_STATIC_BASE_URL || 'http://localhost:806/public'

// 响应式数据
const sidebarOpen = ref(false)
const expandedChapters = ref<number[]>([]) // 存储展开的章节ID
const selectedLecture = ref<Lecture | null>(null)
const lectureContent = ref('')
const tableOfContents = ref<Array<{ id: string, text: string, level: number }>>([])
const contentContainer = ref<HTMLElement | null>(null)
const loading = ref(true)
const error = ref('')

// 所有章节数据
const chapters = ref<Chapter[]>([])

// API调用函数
const fetchChapters = async () => {
  try {
    loading.value = true
    error.value = ''
    
    const response = await fetch(`${API_BASE_URL}/chapters`)
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const data = await response.json()
    
    if (data.success) {
      chapters.value = data.data
      
      // 默认展开第一个章节
      if (chapters.value.length > 0) {
        expandedChapters.value = [chapters.value[0].id]
      }
    } else {
      throw new Error(data.message || '获取章节数据失败')
    }
  } catch (err) {
    console.error('获取章节数据失败:', err)
    error.value = err instanceof Error ? err.message : '获取章节数据失败'
    // 如果API调用失败，使用静态数据作为后备
    chapters.value = [
      {
        id: 1,
        title: '第1次课',
        description: '课程绪论',
        order_index: 1,
        lectures: [
          { id: 1, title: '第01课-绪论', file_type: 'pdf', order_index: 1, chapter_id: 1, file_path: '/chap01/第01课-绪论.pdf' },
          { id: 2, title: '第1次课第1学时教案', file_type: 'markdown', order_index: 2, chapter_id: 1, file_path: '/chap01/第1次课第1学时_教案.md' },
          { id: 3, title: '第1次课第2学时教案', file_type: 'markdown', order_index: 3, chapter_id: 1, file_path: '/chap01/第1次课第2学时_教案.md' }
        ]
      }
    ]
    expandedChapters.value = [1]
  } finally {
    loading.value = false
  }
}



// 工具函数
const isPdfFile = (fileType: string) => {
  return fileType.toLowerCase() === 'pdf'
}

const getCurrentChapter = () => {
  if (!selectedLecture.value) return null
  return chapters.value.find(chapter => 
    chapter.lectures.some(lecture => lecture.id === selectedLecture.value?.id)
  )
}

const toggleSidebar = () => {
  sidebarOpen.value = !sidebarOpen.value
}

const toggleChapter = (chapterId: number) => {
  const index = expandedChapters.value.indexOf(chapterId)
  if (index > -1) {
    expandedChapters.value.splice(index, 1)
  } else {
    expandedChapters.value.push(chapterId)
  }
}

// 生成目录
const generateTableOfContents = (htmlContent: string) => {
  const parser = new DOMParser()
  const doc = parser.parseFromString(htmlContent, 'text/html')
  const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6')

  const toc: Array<{ id: string, text: string, level: number }> = []

  headings.forEach((heading, index) => {
    const level = parseInt(heading.tagName.charAt(1))
    const text = heading.textContent?.trim() || ''
    const id = `heading-${index}`

    // 为标题添加 ID
    heading.id = id

    if (text) {
      toc.push({ id, text, level })
    }
  })

  return { toc, modifiedHtml: doc.body.innerHTML }
}

// 滚动到指定标题
const scrollToHeading = (headingId: string) => {
  if (!contentContainer.value) return

  const targetElement = contentContainer.value.querySelector(`#${headingId}`)
  if (targetElement) {
    // 找到主内容区域的滚动容器
    const scrollContainer = targetElement.closest('.overflow-y-auto')
    if (scrollContainer) {
      // 计算目标元素相对于滚动容器的位置
      const containerRect = scrollContainer.getBoundingClientRect()
      const targetRect = targetElement.getBoundingClientRect()
      const scrollTop = scrollContainer.scrollTop + (targetRect.top - containerRect.top) - 20 // 20px 偏移量
      
      // 在滚动容器内平滑滚动
      scrollContainer.scrollTo({
        top: scrollTop,
        behavior: 'smooth'
      })
    }
  }
}

// 初始化markdown渲染器
const initMarkdownRenderer = async () => {
  // 配置marked选项
  marked.setOptions({
    breaks: true,
    gfm: true
  })
  
  markdownRenderer = {
    render: (markdown: string) => {
      return marked(markdown)
    }
  }
}

// 选择讲义
const selectLecture = async (lecture: Lecture) => {
  selectedLecture.value = lecture
  lectureContent.value = ''
  tableOfContents.value = []
  sidebarOpen.value = false // 移动端选择后关闭侧边栏

  // 如果是PDF文件，不需要加载内容
  if (isPdfFile(lecture.file_type)) {
    return
  }

  // 处理Markdown文件
  try {
    let content = ''
    
    // 从后端服务器获取文件内容
    if (lecture.file_path) {
      // 使用静态文件服务，而不是API路由
      const fileUrl = `${STATIC_BASE_URL}${lecture.file_path}`
      console.log('正在请求文件:', fileUrl)
      const response = await fetch(fileUrl)
      
      if (response.ok) {
        content = await response.text()
        console.log('文件加载成功，内容长度:', content.length)
      } else {
        console.error('文件加载失败:', response.status, response.statusText)
      }
    }
    
    if (content) {
      // 使用marked渲染器
      const htmlContent = markdownRenderer ? markdownRenderer.render(content) : marked(content)

      // 生成目录并修改HTML内容
      const { toc, modifiedHtml } = generateTableOfContents(htmlContent)
      tableOfContents.value = toc
      lectureContent.value = modifiedHtml
      
      // 等待DOM更新
      await nextTick()
    } else {
      lectureContent.value = '<p class="error">无法加载讲义内容</p>'
    }
  } catch (error) {
    lectureContent.value = '<p class="error">加载讲义时发生错误</p>'
  }
}

onMounted(async () => {
  await initMarkdownRenderer()
  await fetchChapters()
})
</script>

<style scoped>
/* Prose 样式增强 */
.prose :deep(h1),
.prose :deep(h2),
.prose :deep(h3),
.prose :deep(h4),
.prose :deep(h5),
.prose :deep(h6) {
  @apply text-gray-900 font-semibold mt-8 mb-4 leading-tight;
}

.prose :deep(h1) {
  @apply text-4xl border-b border-slate-200 pb-2;
}

.prose :deep(h2) {
  @apply text-3xl;
}

.prose :deep(h3) {
  @apply text-2xl;
}

.prose :deep(p) {
  @apply my-5;
}

.prose :deep(a) {
  @apply text-blue-600 underline hover:text-blue-800;
}

.prose :deep(code) {
  @apply bg-slate-100 text-rose-600 px-1.5 py-0.5 rounded text-sm;
  font-family: 'JetBrains Mono', 'Fira Code', Consolas, 'Liberation Mono', Menlo, Courier, monospace;
}

.prose :deep(pre) {
  @apply bg-slate-800 text-slate-200 p-6 rounded-lg overflow-x-auto my-6;
}

.prose :deep(pre code) {
  @apply bg-transparent p-0 rounded-none;
  color: #22c55e;
  font-family: 'Consolas', 'Microsoft YaHei', '微软雅黑', monospace;
}

/* 完全重置所有language-*类的样式 */
.prose :deep(code[class*="language-"]) {
  all: unset !important;
  font-family: 'Consolas', 'Microsoft YaHei', '微软雅黑', monospace !important;
  -webkit-font-smoothing: antialiased !important;
  -moz-osx-font-smoothing: grayscale !important;
  text-rendering: optimizeLegibility !important;
  font-variant-ligatures: none !important;
  font-feature-settings: "liga" 0 !important;
  font-size: 14px !important;
  line-height: 1.6 !important;
  font-weight: 400 !important;
  letter-spacing: 0.025em !important;
  color: #22c55e !important;
  background: transparent !important;
  padding: 0 !important;
  margin: 0 !important;
  border: none !important;
  border-radius: 0 !important;
  box-shadow: none !important;
  text-shadow: none !important;
  display: inline !important;
}

/* 强制覆盖pre内的code标签 */
.prose :deep(pre code[class*="language-"]) {
  all: unset !important;
  font-family: 'Consolas', 'Microsoft YaHei', '微软雅黑', monospace !important;
  -webkit-font-smoothing: antialiased !important;
  -moz-osx-font-smoothing: grayscale !important;
  text-rendering: optimizeLegibility !important;
  font-variant-ligatures: none !important;
  font-feature-settings: "liga" 0 !important;
  font-size: 14px !important;
  line-height: 1.6 !important;
  font-weight: 400 !important;
  letter-spacing: 0.025em !important;
  color: #22c55e !important;
  background: transparent !important;
  padding: 0 !important;
  margin: 0 !important;
  border: none !important;
  border-radius: 0 !important;
  box-shadow: none !important;
  text-shadow: none !important;
  display: inline !important;
}

/* 针对特定的language类 */
.prose :deep(code.language-html),
.prose :deep(code.language-css),
.prose :deep(code.language-js),
.prose :deep(code.language-javascript),
.prose :deep(code.language-text) {
  all: unset !important;
  font-family: 'Consolas', 'Microsoft YaHei', '微软雅黑', monospace !important;
  -webkit-font-smoothing: antialiased !important;
  -moz-osx-font-smoothing: grayscale !important;
  text-rendering: optimizeLegibility !important;
  font-variant-ligatures: none !important;
  font-feature-settings: "liga" 0 !important;
  font-size: 14px !important;
  line-height: 1.6 !important;
  font-weight: 400 !important;
  letter-spacing: 0.025em !important;
  color: #22c55e !important;
  background: transparent !important;
  padding: 0 !important;
  margin: 0 !important;
  border: none !important;
  border-radius: 0 !important;
  box-shadow: none !important;
  text-shadow: none !important;
  display: inline !important;
}

.prose :deep(blockquote) {
  @apply border-l-4 border-blue-600 pl-4 my-6 text-gray-500 italic;
}

.prose :deep(table) {
  @apply w-full border-collapse my-6;
}

.prose :deep(th),
.prose :deep(td) {
  @apply border border-slate-200 p-3 text-left;
}

.prose :deep(th) {
  @apply bg-slate-50 font-semibold;
}

.prose :deep(ul),
.prose :deep(ol) {
  @apply my-5 pl-6;
}

.prose :deep(li) {
  @apply my-2;
}

.error {
  @apply text-red-500 bg-red-50 border border-red-200 rounded-md p-3 my-4;
}

/* 移动端响应式 */
@media (max-width: 768px) {
  .lg\:ml-70 {
    margin-left: 0 !important;
  }
  
  .flex.gap-6 {
    flex-direction: column;
    gap: 1rem;
  }
  
  .w-70.flex-shrink-0 {
    width: 100%;
    order: -1;
  }
  
  .sticky.top-6 {
    position: static;
  }
  
  .text-5xl {
    font-size: 1.875rem;
    line-height: 2.25rem;
  }
  
  .grid.grid-cols-1.sm\:grid-cols-2.lg\:grid-cols-auto-fit {
    grid-template-columns: repeat(1, minmax(0, 1fr));
  }
  
  .text-3xl.font-bold.text-gray-900 {
    font-size: 1.5rem;
    line-height: 2rem;
  }
}

@media (max-width: 480px) {
  .text-5xl {
    font-size: 1.5rem;
    line-height: 2rem;
  }
  
  .p-8 {
    padding: 0.75rem;
  }
}
</style>